import { fromPromise } from '../../universalify/index'
import fs from '../fs'
import path from '../../node/path'
import mkdir from '../mkdirs'
import remove from '../remove'
import errorCode from '../../node/error-code'

function emptyDir (dir) {
    return new Promise((res, rej) => {
        let items;
        try {
            fs.readdir(dir, (e, list) => {
                items = list
                res(Promise.all(items.map(item => remove.remove(path.join(dir, item)))))
            })
        } catch (err) {
            if (err.message === errorCode.errormessage.ENOTDIR) {
                throw err;
            }
            try {
                mkdir.mkdirs(dir, e => {
                    res(e)
                })
            } catch (err) {
            }
        }
    })
}

function emptyDirSync (dir) {
    let items
    try {
        items = fs.readdirSync(dir)
    } catch (err) {
        if (err.message === errorCode.errormessage.ENOTDIR) {
            throw err;
        }
        return mkdir.mkdirsSync(dir)
    }

    items.forEach(item => {
        item = path.join(dir, item)
        remove.removeSync(item)
    })
}

export default {
    emptyDirSync,
    emptydirSync: emptyDirSync,
    emptyDir: fromPromise(emptyDir),
    emptydir: emptyDir
}
